# -*- coding: utf-8 -*-

import hashlib
import json
import time
import requests

from django.conf import settings

from common.utils import exceptions as err
from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)

METIS_KEY = settings.METIS_KEY
METIS_URL = settings.METIS_URL
METIS_CONTROL_URL = settings.METIS_CONTROL_URL


def generate_sign(parameter, _time, key):
    s = ''
    s += '%s%s%s' % (parameter, _time, key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def _base_request(method, data, success_code=[200], throw_exception_if_unavailable=False, is_control=False, timeout=10):
    url = METIS_URL + method
    if is_control:
        url = METIS_CONTROL_URL + method
    key = METIS_KEY
    timestamp = int(time.time())
    headers = {'content-type': 'application/json', 'X-OpCode': 'WI'}
    data = json.dumps(data, separators=(',', ':'))
    sign = generate_sign(data, timestamp, key)
    payload = {"time": timestamp, "sign": sign}
    _LOGGER.info('begin request metis {}, data: {}'.format(method, data))
    resp = requests.post(url, params=payload, headers=headers, data=data, timeout=timeout)
    _LOGGER.info('finish request metis, resp : {}'.format(resp.content))
    if resp.status_code != 200:
        if throw_exception_if_unavailable:
            raise err.ServerError(u'游戏错误')
        return False, None
    else:
        resp_data = json.loads(resp.text)
        if resp_data['code'] in success_code:
            return True, resp_data['data']
        else:
            return False, None


def launch(user_id, user_name, game_id, ref_id, amount, token):
    """
    登入metis并转出资金
    :return: (status, data) status: bool 标识是否成功
                            data: 成功后的数据，失败返回None
    """
    method = '/users/launch'
    data = {'user_id': user_id, 'user_name': user_name,
            'game_id': game_id, 'ref_id': ref_id, 'amount': amount, 'token': token}
    return _base_request(method, data)


def query_balance(user_id):
    method = '/users/queryBalance'
    data = {'user_id': user_id}
    return _base_request(method, data, success_code=[200, 504], throw_exception_if_unavailable=True)


def deposit(user_name, ref_id, amount):
    method = '/users/deposit'
    data = {'user_name': user_name, 'ref_id': ref_id, 'amount': amount}
    return _base_request(method, data)


def withdraw(user_id, ref_id, amount):
    method = '/users/withdraw'
    data = {'user_id': user_id, 'ref_id': ref_id, 'amount': amount}
    return _base_request(method, data, [200, 508])


def withdraw_all(user_id, ref_id):
    method = '/users/withdrawAll'
    data = {'user_id': user_id, 'ref_id': ref_id}
    return _base_request(method, data)


def query_ticket(ref_id):
    method = '/users/queryTicket'
    data = {'ref_id': ref_id}
    return _base_request(method, data)


def query_betlogs_by_id(ticket_id, game_id, page, size):
    """
    查询游戏注单
    """
    method = '/logs/BetLogsByID'
    data = {'ticket_id': ticket_id, 'game_id': game_id,
            'page': page, 'page_size': size}
    return _base_request(method, data, timeout=60)


def query_user_betlogs_by_id(user_id, ticket_id, page, size):
    """
    使用cursor，查询用户下注单
    第一次查询不用带ticket_id
    """
    method = '/logs/UserBetLogsByID'
    data = {'user_id': user_id, 'ticket_id': ticket_id,
            'page': page, 'page_size': size}
    return _base_request(method, data)


def get_pool(game_id):
    """查询水池量
    """
    method = '/getPool'
    data = {'game_id': game_id}
    return _base_request(method, data, is_control=True)


def set_pool(game_id, control_rate=None, control_pool=None):
    """针对水池进行增减量
    :water_rate: 抽水率
    :control_pool: 欲增减的水池量
    """
    method = '/updatePoolMoney'
    data = {'game_id': game_id, 'pool_refund': control_rate,
            'control_money': control_pool}
    return _base_request(method, data, is_control=True)
